package net.hzlj.platform.enterprise.activity;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;

import com.getbase.floatingactionbutton.AddFloatingActionButton;
import com.tencent.bugly.beta.Beta;

import net.hzlj.platform.enterprise.BootApp;
import net.hzlj.platform.enterprise.beans.UserBean;
import net.hzlj.platform.enterprise.beans.ui.Category;
import net.hzlj.platform.enterprise.beans.ui.Column;
import net.hzlj.platform.enterprise.common.EventBusParameter;
import net.hzlj.platform.enterprise.config.HttpConfig;
import net.hzlj.platform.enterprise.helper.ToastHelper;
import net.hzlj.rl.zhangjiajie.R;
import net.hzlj.platform.enterprise.common.Constant;
import net.hzlj.platform.enterprise.fragment.BaseFragment;
import net.hzlj.platform.enterprise.fragment.ProfileFragment;
import net.hzlj.platform.enterprise.service.MainService;
import net.hzlj.platform.enterprise.task.HttpRequestApi;
import net.hzlj.platform.enterprise.task.Task;
import net.hzlj.platform.enterprise.utils.AppPreferencesUtils;
import net.hzlj.platform.enterprise.utils.PreferencesUtils;
import net.hzlj.platform.enterprise.utils.recorder.MediaManager;
import net.hzlj.platform.enterprise.widght.NavTabBottomBar;
import net.hzlj.platform.enterprise.widght.TitleBar;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * @ClassName: HomeActivity
 * @Description: 主页面Activity
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2015-7-25 06:56:09
 */
public class HomeActivity extends BaseActivity {

    private static final String TAG = HomeActivity.class.getSimpleName();

    private MyHandler<HomeActivity> mHandler;

    public static HomeActivity HOME_ACTIVITY;
    //标题栏
    @BindView(R.id.title_bar)
    TitleBar mTitleBar;
    //导航栏
    @BindView(R.id.main_navtab)
    NavTabBottomBar mNavTabBottomBar;
    @BindView(R.id.addFloatingActionButton)
    AddFloatingActionButton mFloatingActionButton;
    //Fragment集合
    private ArrayList<Fragment> mFragments = new ArrayList<Fragment>();

    private ArrayList<Column> mColumns = new ArrayList<Column>();

    private int mCurIndex = 0;
    private int mColumnType = 1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void setRootView() {
        super.setRootView();
        setContentView(R.layout.activity_home);
    }

    @Override
    protected void initTitleBar() {
        super.initTitleBar();
        HOME_ACTIVITY = this;
        mHandler = new MyHandler<HomeActivity>(this);
        mTitleBar.bindActivity(this);
        mNavTabBottomBar.setVisibility(View.GONE);
    }

    @Override
    protected void initData() {
        super.initData();
        Log.i(TAG,"Build.CPU_ABI:" + Build.CPU_ABI);
        BootApp.getInstance().sendBroadcast(Constant.Intent.ACTION_UPDATE_USER_INFO);
        startService(new Intent(this, MainService.class));
        if (!BootApp.getInstance().isLogin()){
            BootApp.getInstance().exitLogin();
            startActivity(new Intent(this,LoginActivity.class));
            finish();
            return;
        }
        mColumns = BootApp.getInstance().COLUMNS;
        setupColumnsFragments(mColumns);
        Beta.checkUpgrade();
    }

    /**
     * 初始化底部导航栏
     *
     * @param columns
     */
    private void setupColumnsFragments(ArrayList<Column> columns) {
        if (columns == null || columns.isEmpty()) {
            return;
        }
        final DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        mNavTabBottomBar.IsScroll(false);
        for (int i = 0; i < columns.size(); i++) {
            Column column = columns.get(i);
            boolean flag = true;
            if (i == columns.size() - 1) {
                flag = false;
            }
            mNavTabBottomBar.addNavChildText(column.columnName, 0, column.columnIconResId, flag);
            mNavTabBottomBar.totalLength = mNavTabBottomBar.totalLength + column.columnName.length();
            BaseFragment fragment = null;
            switch (column.columnType) {
                case 1:
                    //category请求
                    if (column.columnId.equals(Column.COLUMN_ID_PROFILE)) {
                        fragment = new ProfileFragment();//我的
                    }
                    fragment.setTag((Category) column.column);
                    break;
                case 2:
                    //contentInfo请求
                    break;
                case 3:
                    //activity请求
                    if (column.columnId.equals(Column.COLUMN_ID_PROFILE)) {
                        fragment = new ProfileFragment();
                    }
                    fragment.setTag((Category) column.column);
                    break;
            }
            fragment.setArg1(i);
            mFragments.add(fragment);
        }

        final int width = displayMetrics.widthPixels;

        mNavTabBottomBar.setOnNavTabSelectedListener(new NavTabBottomBar.OnNavTabBarSelectedListener() {
            public void onTabSelected(int position) {
            }

            @Override
            public void onTabSelected(int present, int position) {
                // TODO Auto-generated method stub
//            	BootApp.checkNetwork();
                BaseFragment fromFragment = (BaseFragment) mFragments.get(present);
                switchContent(fromFragment, (BaseFragment) mFragments.get(position));
                mCurIndex = position;
                Column column = mColumns.get(mCurIndex);
                mColumnType = column.columnType;
                onClick(mCurIndex);
                //TODO 更新 TitleBar
//                updateTitleBar();
            }
        });
        View containerView = findViewById(R.id.container);
        containerView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            public boolean onPreDraw() {
                mNavTabBottomBar.finishAdd(width, 0);
                return true;
            }
        });

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.add(R.id.main_fragment_container, mFragments.get(mCurIndex)).commit();
        onClick(mCurIndex);
    }

    private void switchContent(BaseFragment from, BaseFragment to) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (!to.isAdded()) {//先判断是否被add过
            //隐藏当前的fragment，add下一个到Activity中
            transaction.hide(from).add(R.id.main_fragment_container, to).commit();
        } else {
            //隐藏当前的fragment，显示下一个
            transaction.hide(from).show(to).commit();
//            to.onFrameResume();
        }
    }

    public void onClick(int mCurIndex) {
        BaseFragment fragment = (BaseFragment) mFragments.get(mCurIndex);
        if (fragment.getNetInitState() == BaseFragment.NetState.INIT_FIRST) {
            fragment.setNetInitState(BaseFragment.NetState.INITING);

            Column column = mColumns.get(mCurIndex);
            Log.i(TAG, "onClick mCurIndex:" + mCurIndex + ",column.columnType:" + column.columnType + ",column.columnId:" + column.columnId);
            switch (column.columnType) {
                case 1:
                    /*if (column.columnId.equals(Column.COLUMN_ID_COMMUNICATION)) {
                        //TODO 请求网络更新数据
                        BaseFragment f = (BaseFragment) mFragments.get(mCurIndex);
                        f.initData(BaseFragment.DataState.DATA_FIRST);
                    } else if (column.columnId.equals(Column.COLUMN_ID_TELEPHONE_REPORTING)) {
                        BaseFragment f = (BaseFragment) mFragments.get(mCurIndex);
                        f.initData(BaseFragment.DataState.DATA_FIRST);
                    } else if (column.columnId.equals(Column.COLUMN_ID_PROFILE)) {
                        BaseFragment f = (BaseFragment) mFragments.get(mCurIndex);
                        f.initData(BaseFragment.DataState.DATA_FIRST);
                    }*/
                    BaseFragment f = (BaseFragment) mFragments.get(mCurIndex);
                    f.initData(BaseFragment.DataState.DATA_FIRST);
                    break;
                case 2:
                    break;
                case 3:
                    break;
                default:
                    break;
            }

        } else {
            fragment.onFrameResume();
        }
        refreshTitleBar();
    }

    //刷新标题栏
    public void refreshTitleBar() {
        String titleName = BootApp.getInstance().mColumnNames[mCurIndex];
        mTitleBar.setDisplayName(titleName);

        switch (mCurIndex) {
            case 0:
                //TODO 我
                mTitleBar.setOnMainLeftClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                }, R.drawable.ic_search_selector, View.INVISIBLE);
                mTitleBar.setOnMainRightClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                }, R.drawable.ic_setting_selector, View.INVISIBLE);
                mFloatingActionButton.setVisibility(View.GONE);
                break;
        }
    }

    @OnClick(R.id.addFloatingActionButton)
    public void onClick() {

    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "onDestroy.....");
        HOME_ACTIVITY = null;
        MediaManager.release();
    }

    @Override
    protected void onEventRunBackground(EventBusParameter parameter) {
        super.onEventRunBackground(parameter);
    }

    @Override
    public void onTaskResult(Task task) {
        super.onTaskResult(task);
    }

    @Override
    void handleMessage(BaseActivity activity, Message msg) {

    }
}
